﻿using System;
using System.Configuration;
using System.Web;
using System.IO;

namespace Shuba.Web.bulk_upload
{
    public partial class pipeline_upload : basePage
    {
        string msg;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string acl = GetUserAccess("MSTR_PIPELINE");
                if (!IsUserAdd(acl))
                {
                    msg = GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                    AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
                }
                LabelTitle.Text = GetPageTitle("MSTR_PIPELINE");
            }
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                lblStatus.Text = "";
                status.Visible = false;
            }
            if (IsPostBack)
            {
                Boolean fileOK = false;
                string path = Server.MapPath("~/uploads/");
                string ErrMessage = "";
                int ErrLine = 0;

                if (FileUpload1.HasFile)
                {
                    String fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower();
                    String[] allowedExtensions = { ".txt", ".csv" };
                    for (int i = 0; i < allowedExtensions.Length; i++)
                    {
                        if (fileExtension == allowedExtensions[i])
                        {
                            fileOK = true;
                        }
                    }
                    if (!FileUpload1.FileName.ToLower().Trim().Substring(0, 8).Contains("pipeline")) fileOK = false;
                }

                if (fileOK)
                {
                    status.Visible = true;

                    DateTime TglRencanaKunjungan = ProcessingDate().AddDays(1);

                    string fName = path + Session["UserID"].ToString() + FileUpload1.FileName;
                    FileUpload1.PostedFile.SaveAs(fName);

                    var filestream = File.OpenText(fName);
                    string contents = filestream.ReadToEnd();
                    filestream.Close();

                    var bllFile = new Business.Pipeline();
                    Model.PipelineInfo Info;

                    var bllBranch = new Shuba.Business.Branch();

                    char rowDelimiter = '\n';
                    char fldDelimiter = '\t';

                    //CultureInfo ci = new CultureInfo("id-ID");

                    var rows = contents.Split(rowDelimiter);
                    var FieldCount = rows[0].Split(fldDelimiter);

                    int SuccessCount = 0;

                    try
                    {
                        for (var i = 1; i < rows.Length; i++)
                        {
                            var fields = rows[i].Split(fldDelimiter);

                            if (fields.Length > 1)
                            {
                                /*
                                if (fields[5].Trim() != string.Empty)
                                {
                                    if (!IsValidEntryFormat(fields[5].Trim(), "D"))
                                    {
                                        ErrMessage = "<BR> Invalid Value or Format at Column : 6, Line :" + i.ToString();
                                    }
                                    else TglLahir = Convert.ToDateTime(fields[5].Trim());
                                }
                                else TglLahir = Convert.ToDateTime("01-01-1900");
                                */

                                //if (!IsValidEntryFormat(fields[0].Trim(), "N")) ErrMessage = "<BR> Invalid CIF Value or Format at Column : 1, Line :" + i.ToString();
                                if (!IsValidEntryFormat(fields[3].Trim().Replace(",", ""), "M")) ErrMessage = "<BR> Invalid Rencana Plafon Value or Format at Column : 4, Line :" + i.ToString();
                                if (!IsValidEntryFormat(fields[4].Trim(), "NS") || !IsValidEntryFormat(fields[5].Trim(), "NS") || !IsValidEntryFormat(fields[6].Trim(), "NS")) ErrMessage += "<BR> Invalid Phone Number Value or Format at Column : [5 or 6 or 7], Line :" + i.ToString();
                                if (fields[1].Trim() == "") ErrMessage = "<BR> Invalid Debtor Name at Column : 2, Line :" + i.ToString();

                                //if
                                //(
                                //    fields[7].Trim() == "" && //kodya
                                //    fields[8].Trim() == "" && //kecamatan
                                //    fields[9].Trim() == "" && //kelurahan
                                //    fields[10].Trim() == "" && //address
                                //    fields[11].Trim() == "" //zip
                                //)
                                //{
                                //    ErrMessage = "<BR> Invalid Data, Check Data Completeness at Column: 8,9,10,11 and 12 at Line :" + i.ToString();
                                //}

                                if (bllBranch.Get(fields[0].Trim()).BranchID == null) ErrMessage = "<BR> Invalid Unit Code at Column : 1, Line :" + i.ToString();
                                if (!Shuba.Business.ChannelMapping.CheckExistingCombination2(fields[14].Trim(), fields[12].Trim(), fields[13].Trim()))
                                {
                                    ErrMessage = "<BR> Invalid Channel Relationship Combination at Line :" + i.ToString();
                                }
                                if (bllFile.IsExist(fields[0].Trim(), fields[1].Trim(), fields[7].Trim(), fields[10].Trim())) ErrMessage = "<BR> Already Pipeline Combination Unit Code, FullName, Kodya and Address at Column : 1,2,8,11 Line :" + i.ToString();

                                if (ErrMessage == "")
                                {
                                    Info = new Shuba.Model.PipelineInfo();
                                    Info.UNIT_CODE = fields[0].Trim();
                                    Info.FULL_NAME = fields[1].Trim();
                                    Info.JENIS_USAHA = fields[2].Trim();
                                    Info.RENCANA_PLAFON = fields[3].Trim() == "" ? 0 : Convert.ToDouble(fields[3].Trim().Replace(",", ""));
                                    Info.MOBILE_PHONE = fields[4].Trim();
                                    Info.OFFICE_PHONE = fields[5].Trim();
                                    Info.RESIDENTIAL_PHONE = fields[6].Trim();
                                    Info.KODYA_KAB_BUSINESS = fields[7].Trim();
                                    Info.KECAMATAN_BUSINESS = fields[8].Trim();
                                    Info.KELURAHAN_BUSINESS = fields[9].Trim();
                                    Info.ADDRESS_BUSINESS = fields[10].Trim();
                                    Info.ZIP_CODE_BUSINESS = fields[11].Trim();
                                    Info.DATE_VISIT_PLAN = TglRencanaKunjungan;
                                    Info.PROSPECT_TYPE = fields[12].Trim();
                                    Info.DEBTOR_TYPE = fields[13].Trim();
                                    Info.CHANNELING = fields[14].Trim();
                                    Info.OMZET_1 = fields[15].Trim() == "" ? 0 : Convert.ToDouble(fields[15].Trim().Replace(",", ""));
                                    Info.OMZET_2 = fields[16].Trim() == "" ? 0 : Convert.ToDouble(fields[16].Trim().Replace(",", ""));
                                    Info.OMZET_3 = fields[17].Trim() == "" ? 0 : Convert.ToDouble(fields[17].Trim().Replace(",", ""));
                                    Info.OMZET_4 = fields[18].Trim() == "" ? 0 : Convert.ToDouble(fields[18].Trim().Replace(",", ""));
                                    Info.OMZET_5 = fields[19].Trim() == "" ? 0 : Convert.ToDouble(fields[19].Trim().Replace(",", ""));
                                    Info.OMZET_6 = fields[20].Trim() == "" ? 0 : Convert.ToDouble(fields[20].Trim().Replace(",", ""));
                                    Info.OMZET_7 = fields[21].Trim() == "" ? 0 : Convert.ToDouble(fields[21].Trim().Replace(",", ""));
                                    Info.OMZET_8 = fields[22].Trim() == "" ? 0 : Convert.ToDouble(fields[22].Trim().Replace(",", ""));
                                    Info.OMZET_9 = fields[23].Trim() == "" ? 0 : Convert.ToDouble(fields[23].Trim().Replace(",", ""));
                                    Info.OMZET_10 = fields[24].Trim() == "" ? 0 : Convert.ToDouble(fields[24].Trim().Replace(",", ""));
                                    Info.OMZET_11 = fields[25].Trim() == "" ? 0 : Convert.ToDouble(fields[25].Trim().Replace(",", ""));
                                    Info.OMZET_12 = fields[26].Trim() == "" ? 0 : Convert.ToDouble(fields[26].Trim().Replace(",", ""));
                                    Info.OMZET_AVERAGE = fields[27].Trim() == "" ? 0 : Convert.ToDouble(fields[27].Trim().Replace(",", ""));
                                    Info.ACT_TYPE = "UPLOAD";
                                    Info.ENTRY_BY = HttpContext.Current.User.Identity.Name;
                                    Info.ENTRY_DATE = ProcessingDate();
                                    Info.UPDATE_BY = HttpContext.Current.User.Identity.Name;
                                    Info.UPDATE_DATE = ProcessingDate();
                                    Info.EKSTERNAL = fields.Length < 29 ? "" : fields[28].Trim();
                                    Info.REFERENSI = fields.Length < 30 ? "" : fields[29].Trim();
                                    if (bllFile.Save(Info) > 0) SuccessCount++;
                                }
                                else
                                {
                                    ErrLine = i;
                                    i = rows.Length;
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrMessage += GetGlobalResourceObject("Messages", "UploadFailAlert").ToString();
                        ErrMessage += "<br>" + ex.Message + "<br><br>Please check your data";
                        ErrMessage += "<br>" + ex.Message + "<br><br>File Successfully Uploaded\\n\\nSuccessfully Upload : " + SuccessCount + " Record(s)";
                    }

                    File.Delete(fName);
                    AddLog("UPLOAD", "UPLOAD TOPUP");

                    if (ErrMessage == "")
                    {
                        FileUpLoadValidator.Visible = false;
                        msg = "File Successfully Uploaded\\n\\nSuccessfully Upload : " + SuccessCount + " Record(s)";//this.GetGlobalResourceObject("Messages", "UploadSuccessAlert").ToString();
                        AlertAndRedirect(msg, "pipeline_list.aspx");
                    }
                    else
                    {
                        status.Visible = true;
                        lblStatus.Text = "<b>Error Found:</b><br>" + ErrMessage + "<br><br><b>Upload Process Stoped at Line: " + ErrLine + "</b>";
                        FileUpLoadValidator.Visible = false;
                    }
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("pipeline_list.aspx");
        }
    }
}
